package com.smtx.service.impl;

import com.smtx.service.Node;
import com.smtx.service.Repository;
import com.smtx.service.SimpleRepository;

import javax.naming.OperationNotSupportedException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 17.04.11
 * Time: 1:16
 * To change this template use File | Settings | File Templates.
 */
public class NodeImpl extends java.io.File implements Node {
    protected SimpleRepository rep;

    public NodeImpl(String s) throws IOException {
        super(s);
    }

    @Override
    public String getReference() {
        return String.format("%s:%s%s", getRep(), getPath(), getName());
    }

    @Override
    public Boolean isExists() {
        return super.exists();
    }

    @Override
    public List<Node> listChildren() {
        List<Node> res = new ArrayList<Node>();
        for (java.io.File f : this.listFiles())
            try {
                res.add( getRep().getNode(f.getPath()) );
            } catch (IOException e) {
                e.printStackTrace();
            }
        return res;
    }

    @Override
    public Node getParentNode() throws IOException {
        return getRep().getNode(this.getParentFile().getPath());
    }

    @Override
    public void create() throws IOException {
        super.mkdirs();
        if (this.isFile())
            super.createNewFile();
    }

    @Override
    public void remove() {
        super.delete();
    }

    @Override
    public void clean() {
        for (Node n : listChildren())
            try {
                n.remove();
            } catch (OperationNotSupportedException e) {
                e.printStackTrace();
            }
    }

    protected SimpleRepository getRep() {
        return rep;
    }
}
